package com.luxk.dbt;

import java.util.Iterator;

public class ExecBlockThread extends ExecBlock {
	
	private int repeat = -1;
	private int duration = 0;
	
	private WorkThread4Perf wthr = null;

	public ExecBlockThread(String name, ExecIF parent, MainContext mCtx) {
		super(name, parent, mCtx);
		this.name = name;
		this.parent = parent;
		this.mCtx = mCtx;
		
		this.result = new Result(this, name);
	}
	
	@Override
	public ExecIF duplicate(ExecIF parent) throws DBTException, DataException {
		ExecBlockThread exec =
				new ExecBlockThread(this.name, parent, this.mCtx);
		
		exec.setRepeat(this.repeat);
		exec.setDuration(this.duration);
		
		Iterator<DataIF> tmp = this.data.values().iterator();
		while(tmp.hasNext()) {
			DataIF data = tmp.next().duplicate();
			exec.addData(data);
		}
		
		for(ExecIF e: this.children) {
			ExecIF child = e.duplicate(exec);
			exec.addChild(child);
		}
		
		return exec;
	}

	@Override
	public void prepareInternal() throws DBTException, DataException {
		this.wthr = new WorkThread4Perf(this.name, this.mCtx);
		this.wthr.setDuration(this.duration);
		this.wthr.setRepeat(this.repeat);
		this.wthr.setExec(this.children);
		
		if(this.mCtx.isDebug())
			this.mCtx.writeDebug("WorkThread(" + this.name + ") initialized");
	}
	
	@Override
	public void runInternal() throws DBTException {
		
		this.result.begin();
		
		// start work thread
		this.wthr.start();

		this.result.setSuccess();
	}

	@Override
	public void cleanupInternal() throws DBTException {
		this.wthr = null;
	}
	
	public boolean isFinished() {
		return this.wthr.isFinished();
	}

	public int getRepeat() {
		return repeat;
	}

	public void setRepeat(int val) {
		this.repeat = val;
	}

	public int getDuration() {
		return duration;
	}

	public void setDuration(int val) {
		this.duration = val;
	}
}
